package top.soft.windows;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import top.soft.inter.Observer;
import top.soft.util.CommonData;

/**
 * @ClassName: CharView
 * @Author: Amosen
 * @Since: 2021/4/21
 */

// 这个类用于聊天选项卡，给予接收消息和发送消息的功能
// ChatView是一个观察者，接收从主界面窗口发来的消息
public class ChatView extends JPanel implements Observer {

	private JSplitPane splitPane;
	private JTextArea historyArea;
	private JTextField inputField;
	private JPanel panelLeft, panelRight;

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

	private ArrayList<String> chatterList = new ArrayList<String>();

	public ChatView() {
		init();
	}

	private void init() {
		register();
		JPanel contentPanel = new JPanel();
		contentPanel.setLayout(new BorderLayout());

		historyArea = new JTextArea(30, 40);
		historyArea.setSize(600, 290);
		historyArea.setEditable(false);
		JScrollPane historyScrollPane = new JScrollPane();
		historyScrollPane.setViewportView(historyArea);
		contentPanel.add(historyScrollPane, BorderLayout.NORTH);

		inputField = new JTextField(40);
		inputField.setSize(600, 100);
		JScrollPane inputScrollPane = new JScrollPane();
		inputScrollPane.add(inputField);
		contentPanel.add(inputField, BorderLayout.CENTER);

		JButton sendBtn = new JButton("发送");
		JButton resetButton = new JButton("重置");
		JPanel btnArea = new JPanel();
		btnArea.setLayout(new FlowLayout(FlowLayout.RIGHT));
		btnArea.add(sendBtn);
		btnArea.add(resetButton);
		contentPanel.add(btnArea, BorderLayout.SOUTH);

		add(contentPanel);

		inputField.addKeyListener(new InputKeyListener());
		sendBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doSend();
			}
		});

		resetButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				doReset();
			}
		});

	}

	private class InputKeyListener extends KeyAdapter {
		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			if (e.getKeyChar() == KeyEvent.VK_ENTER) {
				doSend();
			}
		}
	}

	private void getChatterList(String message) {
		try {
			ObjectMapper om = new ObjectMapper();
			ArrayList<String> users = om.readValue(message, ArrayList.class);
			this.chatterList = users;
		} catch (Exception e) {
			// TODO: handle exception
			return;
		}

	}

	private void doSend() {
		String inputStr = this.inputField.getText();
		if (inputStr == null) {
			return;
		} else {
			if ("".equals(inputStr) || inputStr.length() == 0) {
				return;
			} else {
				// 获取当前时间
				Date date = new Date();
				// 将消息封装起来发送
				Map<String, String> message = new HashMap<>();
				message.put("message", inputStr);
				message.put("time", sdf.format(date));
				ObjectMapper om = new ObjectMapper();
				try {
					String messageStr = om.writeValueAsString(message);
					CommonData.getWebSocketClient().send(messageStr);
					doReset();
				} catch (JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private void doReset() {
		inputField.setText("");
	}

	private void doAccept(String message) {
		ObjectMapper om = new ObjectMapper();
		try {
			Map<String, Object> messageMap = om.readValue(message, Map.class);
			String fromUserId;
			String time;
			String text;
			if (messageMap.containsKey("fromUserId")) {
				fromUserId = (String) messageMap.get("fromUserId");
				time = (String) messageMap.get("time");
				text = (String) messageMap.get("message");

				// 将消息添加到面板上
				historyArea.append(fromUserId + " " + time + "\n");
				historyArea.append(text + "\n");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return;
		}
	}

	// 向主界面注册
	@Override
	public void register() {
		// TODO Auto-generated method stub
		CommonData.getMainWindow().register(this);
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub
		CommonData.getMainWindow().removeObserver(this);
	}

	@Override
	public void acceptAnounce(String message) {
		// TODO Auto-generated method stub
		this.doAccept(message);
		this.getChatterList(message);
	}
}
